const express = require('express');
const router = express.Router();
const dashboardService = require('../../services/dashboardService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 获取数据大屏概览
 */
router.get('/overview', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const overview = await dashboardService.getDashboardOverview();

    res.json({
      success: true,
      data: overview
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取数据概览失败',
      error: error.message
    });
  }
});

/**
 * 获取实时趋势数据
 */
router.get('/trends', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const { hours = 24 } = req.query;
    const trends = await dashboardService.getRealTimeTrends(parseInt(hours));

    res.json({
      success: true,
      data: trends
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取趋势数据失败',
      error: error.message
    });
  }
});

/**
 * 获取系统健康状态
 */
router.get('/health', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const health = await dashboardService.getSystemHealth();

    res.json({
      success: true,
      data: health
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取系统健康状态失败',
      error: error.message
    });
  }
});

/**
 * 获取热门数据排行
 */
router.get('/rankings', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const rankings = await dashboardService.getTopRankings();

    res.json({
      success: true,
      data: rankings
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取排行数据失败',
      error: error.message
    });
  }
});

/**
 * 获取地理分布数据
 */
router.get('/geographic', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const geographic = await dashboardService.getGeographicData();

    res.json({
      success: true,
      data: geographic
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取地理分布数据失败',
      error: error.message
    });
  }
});

/**
 * 获取异常监控数据
 */
router.get('/anomaly', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    const anomaly = await dashboardService.getAnomalyDetection();

    res.json({
      success: true,
      data: anomaly
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取异常监控数据失败',
      error: error.message
    });
  }
});

/**
 * 获取实时数据（WebSocket 或 SSE 可用）
 */
router.get('/realtime', adminAuth, checkPermission('system', 'dashboard'), async (req, res) => {
  try {
    // 设置 SSE 响应头
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Cache-Control'
    });

    // 发送初始数据
    const sendData = async () => {
      try {
        const overview = await dashboardService.getDashboardOverview();
        const health = await dashboardService.getSystemHealth();
        
        const data = {
          timestamp: new Date().toISOString(),
          overview,
          health
        };

        res.write(`data: ${JSON.stringify(data)}\n\n`);
      } catch (error) {
        console.error('SSE data error:', error);
      }
    };

    // 立即发送一次数据
    await sendData();

    // 每30秒发送一次更新
    const interval = setInterval(sendData, 30000);

    // 客户端断开连接时清理
    req.on('close', () => {
      clearInterval(interval);
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      message: '建立实时连接失败',
      error: error.message
    });
  }
});

module.exports = router;